package com.aaa.pdfdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.github.barteksc.pdfviewer.PDFView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 复制assets文件
 * 解压文件
 * 加载本地html
 * WebView通过js加载本地pdf
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private static final int Permission_Request_Code = 110;
    private static final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        if (!isAllPermissionsGranted(permissions)) {
            requestPermissions(permissions);
        }
    }

    private void initView() {
        Button btnWebView = findViewById(R.id.btn_use_webView);
        PDFView pdfView = findViewById(R.id.pdfView);
        mWebView = findViewById(R.id.webView);

        btnWebView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pdfView.setVisibility(View.GONE);
                mWebView.setVisibility(View.VISIBLE);

                File pdfHtmlFile = new File(getFilesDir(), "pdfjs-2.9.359-dist/web/viewer.html");
                if (!pdfHtmlFile.exists()) {
                    File pdfHZipFile = new File(getFilesDir(), "pdfjs-2.9.359-dist.zip");
                    File pdfFolderFile = new File(getFilesDir(), "pdfjs-2.9.359-dist");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            boolean isCopyAssetsSuccess = FileUtils.cpAssetsFile2(getApplicationContext(),
                                    "pdfjs-2.9.359-dist.zip", pdfHZipFile.getAbsolutePath());
                            Log.d(TAG, "isCopyAssetsSuccess: " + isCopyAssetsSuccess);
                            if (isCopyAssetsSuccess) {
                                FileUtils.unZipFile(pdfHZipFile, pdfFolderFile.getAbsolutePath(), new FileUtils.ZipCallback() {
                                    @Override
                                    public void onSuccess() {
                                        useWebViewLoadPdf();
                                    }

                                    @Override
                                    public void onError(String msg) {

                                    }
                                });
                            }

                        }
                    }).start();
                } else {
                    useWebViewLoadPdf();
                }
            }
        });

        // 初始化WebView
        WebSettings settings = mWebView.getSettings();
        settings.setSavePassword(false);
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setBuiltInZoomControls(true);

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient());

    }

    private void useWebViewLoadPdf() {
        String absolutePath = getExternalCacheDir().getAbsolutePath();
        File file = new File(absolutePath, "test3.pdf");
        String pdfPath = file.getAbsolutePath();
        Log.d(TAG, "使用WebView加载PDF: pdfPath=" + pdfPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//api >= 19
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    // https://www.jianshu.com/p/b44580ba70e3
                    // mWebView.loadUrl("file:///android_asset/pdfjs-2.9.359-dist/web/viewer.html?file=" + pdfPath);
                    File pdfHtmlFile = new File(getFilesDir(), "pdfjs-2.9.359-dist/web/viewer.html");
                    String pdfUrl = "file://" + pdfHtmlFile.getAbsolutePath() + "?file=" + pdfPath;
                    Log.d(TAG, "pdfUrl: " + pdfUrl);
                    mWebView.loadUrl(pdfUrl);
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");

        if (isAllPermissionsGranted(permissions)) {
            doAfterPermission();
        } else {
            Toast.makeText(getApplicationContext(), "请前往设置授予权限", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause: isFinishing=" + isFinishing());
    }

    /**
     * 获得权限后该执行的
     */
    public void doAfterPermission() {
        OpenAccountPdfManager.getInstance(getApplicationContext()).createPdf();

        PDFView pdfView = findViewById(R.id.pdfView);
        OpenAccountPdfManager.getInstance(getApplicationContext()).readPdf(pdfView);
    }

    /**
     * 是否已获得相应权限
     *
     * @return false 有未获得的权限
     */
    public boolean isAllPermissionsGranted(String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "isAllPermissionsGranted: permissions=" + permission + ":denied");
                    return false;
                }
            }
            return true;
        } else {
            return true;
        }
    }

    /**
     * 请求授予权限
     */
    public void requestPermissions(String... permissions) {
        Log.i(TAG, "requestPermissions: ");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();
            for (String permission : permissions) {
                boolean showRequestPermissionRationale = shouldShowRequestPermissionRationale(permission);
                Log.i(TAG, "requestPermissions: " + permission + " showRequestPermissionRationale=" + showRequestPermissionRationale);
                // if (showRequestPermissionRationale) {
                // https://blog.csdn.net/wangpf2011/article/details/80589648
                permissionList.add(permission);
                // }
            }
            int size = permissionList.size();
            if (size > 0) {
                String[] strings = new String[size];
                permissionList.toArray(strings);
                printArray(strings);
                requestPermissions(strings, Permission_Request_Code);
            }
        }
    }

    private void printArray(String... strings) {
        if (strings != null) {
            Log.i(TAG, " ");
            for (String string : strings) {
                Log.i(TAG, "printArray: " + string);
            }
        }
    }

    /**
     * 返回权限申请的结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "onRequestPermissionsResult: requestCode=" + requestCode);
        if (requestCode == Permission_Request_Code) {
            boolean allGranted = true;
            boolean granted;
            for (int i = 0; i < permissions.length; i++) {
                granted = grantResult(grantResults[i]);
                if (!granted) {
                    allGranted = false;
                }
                Log.i(TAG, "onRequestPermissionsResult: " + permissions[i] + ":" + grantResult(granted));
            }
            Log.i(TAG, "onRequestPermissionsResult: allGranted=" + allGranted);
            if (allGranted) {
                doAfterPermission();
            }
        }
    }

    public boolean grantResult(int grantId) {
        return grantId == PackageManager.PERMISSION_GRANTED;
    }

    public String grantResult(boolean granted) {
        return granted ? "granted" : "denied";
    }

}
